﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Xml;
using Microsoft.Win32;
using System.IO;
using System.Runtime.InteropServices;


namespace sentence
{
    public partial class MainForm : Form
    {
        XmlDocument xmldoc;
        bool SaveDesktop;
        String SavePath = System.IO.Path.GetTempPath();

        public enum ScreenRatio { SixteenByTen, SixteenByNine, FourByThree, NO_MATCH }

        public MainForm()
        {
            InitializeComponent();
            //判断自动启动设置
            if(File.Exists(@"config.xml"))
            {
                xmldoc = new XmlDocument();
                xmldoc.Load(@"config.xml");
                XmlNode node = xmldoc.GetElementsByTagName("AutoStart").Item(0);
                RegistryKey HKLM = Registry.CurrentUser;
                RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");
                Object path = Run.GetValue(System.Windows.Forms.Application.ProductName);
                if (path != null && path.ToString() != "\"" + System.Windows.Forms.Application.ExecutablePath + "\"")
                {
                    if (node.InnerText.ToString() == "True")
                    {
                        Run.SetValue(System.Windows.Forms.Application.ProductName, "\"" + System.Windows.Forms.Application.ExecutablePath + "\"");
                        HKLM.Close();
                    }
                    else
                    {
                        Run.DeleteValue(System.Windows.Forms.Application.ProductName);
                        HKLM.Close();
                    }
                }
                node = xmldoc.GetElementsByTagName("AutoExit").Item(0);
                if (node.InnerText.ToString() == "True")
                {
                    Thread Thread_AutoExit = new Thread(new ThreadStart(AutoExitThread));
                    Thread_AutoExit.IsBackground = true;
                    Thread_AutoExit.Start();
                }
                node = xmldoc.GetElementsByTagName("Save").Item(0);
                SaveDesktop = (node.InnerText.ToString() == "True") ? true : false;
                if(SaveDesktop)
                {
                    node = xmldoc.GetElementsByTagName("SavePath").Item(0);
                    SavePath = node.InnerText.ToString();
                }
            }
            else
            {
                ConfigForm configForm = new ConfigForm();
                configForm.Show();
            }
            Thread Thread_CheckDesktop = new Thread(new ThreadStart(CheckDesktopThread));
            Thread_CheckDesktop.IsBackground = true;
            Thread_CheckDesktop.Start();

        }

        private void AutoExitThread()
        {
            Thread.Sleep(5*60*1000);
            Application.Exit();
        }

        public static ScreenRatio MainScreenRatio = GetScreenRatio();

        public static ScreenRatio GetScreenRatio()
        {
            int width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
            int height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
            double screen_ratio = (double)width / height;
            if (screen_ratio == 1.6)
            {
                return ScreenRatio.SixteenByTen;
            }
            else if (screen_ratio * (3.0 / 4) == 1 || screen_ratio * (4.0 / 5) == 1)
            {
                return ScreenRatio.FourByThree;
            }
            else if (screen_ratio > 1.77 && screen_ratio < 1.78)
            {
                return ScreenRatio.SixteenByNine;
            }
            else
            {
                return ScreenRatio.NO_MATCH;
            }
        }

        private void CheckDesktopThread()
        {
            String Date = DateTime.Now.ToString("yyyyMMdd");
            String DownloadURL = "http://sentence.sinaapp.com/download.php";
            switch (MainScreenRatio)
            {
                case ScreenRatio.SixteenByTen://1920x1200
                    DownloadURL += "?date=" + Date + "&ScreenRatio=0";
                    break;
                case ScreenRatio.SixteenByNine://1920x1080
                    DownloadURL += "?date=" + Date + "&ScreenRatio=1";
                    break;
                case ScreenRatio.FourByThree://1600x1200
                    DownloadURL += "?date=" + Date + "&ScreenRatio=2";
                    break;
                case ScreenRatio.NO_MATCH:
                    DownloadURL += "?date=" + Date + "&ScreenRatio=0";
                    break;
            }
//             MessageBox.Show(DownloadURL);
//             System.Diagnostics.Process.Start(DownloadURL); 
            applyWallpaperWin7("c:\\1.jpg");

        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

       /* private void applyWallpaperXP(string path)
        {
            RegistryKey myRegKey = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true);
            myRegKey.SetValue("TileWallpaper", "0");
            myRegKey.SetValue("WallpaperStyle", "2");
            myRegKey.Close();
            Bitmap bmpWallpaper = new Bitmap(path);

            string savePath = "";
            if (System.Environment.OSVersion.Version.Major < 6)
            {
                savePath = Path.Combine(MotivateDesktopUtility.ApplicationDirectory, "DonotDelete-TranscodedWallpaper.bmp");
            }
            else
            {
                savePath = Path.Combine(MotivateDesktopUtility.WorkingDirectory, "DonotDelete-TranscodedWallpaper.bmp");
            }
            bmpWallpaper.Save(savePath, ImageFormat.Bmp);

            SystemParametersInfo(20, 1, savePath, 1);
            downloadAndApplyWallpaperSucceeded();
        }*/

        private void applyWallpaperWin7(string path)
        {
            //以拉伸显示壁纸
            RegistryKey myRegKey = Registry.CurrentUser.OpenSubKey("Control Panel\\desktop", true);
            myRegKey.SetValue("TileWallpaper", "0");
            myRegKey.SetValue("WallpaperStyle", "2");
            myRegKey.Close(); 
            
            Shell32.Shell shell = new Shell32.ShellClass();
            Shell32.Folder folder = shell.NameSpace(Path.GetDirectoryName(path)) as Shell32.Folder;
            Shell32.FolderItem folderItem = folder.ParseName(System.IO.Path.GetFileName(path));
            Shell32.FolderItemVerbs vs = folderItem.Verbs();

            bool wallpaperSet = false;
            for (int i = 0; i < vs.Count; i++)
            {
                Shell32.FolderItemVerb ib = vs.Item(i);

                if (ib.Name.Contains("&b") || ib.Name.Contains("&B"))
                {
                    if (ib.Name.ToLower().Contains("background") || ib.Name.ToLower().Contains("背景"))
                    {
                        wallpaperSet = true;
                        ib.DoIt();
                    }
                }
            }

//             if (wallpaperSet == false)
//             {
//                 applyWallpaperXP(path);
//             }
//             else
//             {
//                 downloadAndApplyWallpaperSucceeded();
//             }
        }


        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConfigForm configForm = new ConfigForm();
            configForm.Show();
        }

        private void 关于SentenceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm aboutForm = new AboutForm();
            aboutForm.Show();
        }

    }
}
